package com.gxa.jjty.admin.service.impl;

import com.gxa.jjty.admin.mapper.HealthyMapper;
import com.gxa.jjty.admin.mapper.ScoreMapper;
import com.gxa.jjty.admin.service.HealthyService;
import com.gxa.jjty.core.common.ExceptionCode;
import com.gxa.jjty.core.common.JsonResult;
import com.gxa.jjty.core.exception.BusinessException;
import com.gxa.jjty.core.pojo.HealthWhere;
import com.gxa.jjty.core.pojo.Healthy;
import com.gxa.jjty.core.pojo.HealthyDetails;
import com.gxa.jjty.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author asus
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class HealthyServiceImpl extends BaseServiceImpl<Healthy>  implements HealthyService {

    @Autowired
    ScoreMapper scoreMapper;

    @Autowired
    private  Mapper<Healthy> mapper;

    @Autowired
    private HealthyMapper healthyMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public static final String[] SCORES ={"heartRateList","bloodGlucoseList","bloodOxygenList","bloodFatList","bloodPressureList","foodList","recitalList","healthy:"};
    public static final String HEALTHY="healthy:";

    @Override
    public Map<String, Object> update(Healthy healthy) throws BusinessException {

        //List list = (List) redisTemplate.opsForValue().get("scores");
        Map<String, List<Map<String,Object>>> scores = (Map<String, List<Map<String,Object>>>) redisTemplate.opsForValue().get("scores");
        if (scores==null){
            scores = new HashMap<>(16);
            List<Map<String,Object>> heartRates = scoreMapper.selectByName("心率");
            List<Map<String,Object>> bloodGlucoses = scoreMapper.selectByName("血糖");
            List<Map<String,Object>> bloodOxygens = scoreMapper.selectByName("血氧");
            List<Map<String,Object>> bloodFats = scoreMapper.selectByName("血脂");
            List<Map<String,Object>> bloodPressures = scoreMapper.selectByName("血压");
            List<Map<String,Object>> foods = scoreMapper.selectByName("膳食");
            List<Map<String,Object>> recitals = scoreMapper.selectScore();
            scores.put(SCORES[0], heartRates);
            scores.put(SCORES[1], bloodGlucoses);
            scores.put(SCORES[2], bloodOxygens);
            scores.put(SCORES[3], bloodFats);
            scores.put(SCORES[4], bloodPressures);
            scores.put(SCORES[5], foods);
            scores.put(SCORES[6], recitals);
            redisTemplate.opsForValue().set("scores",scores);
        }
        if (healthy.getHeartRate() != null || healthy.getBloodGlucose() != null || healthy.getBloodOxygen() != null ||
        healthy.getBloodFat() != null || healthy.getBloodFat() != null || healthy.getBloodFat() != null ){

            Example example = new Example(Healthy.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("handicappedId",healthy.getHandicappedId());
            List<Healthy> healthies = mapper.selectByExample(example);
            Integer totalScore = healthies.get(0).getScore();

            if (healthy.getHeartRate() != null){
                //设置心率表现
                for (Map<String, Object> scoreList : scores.get(SCORES[0])) {
                    if (Double.parseDouble(scoreList.get("start").toString())<=healthy.getHeartRate()
                            && healthy.getHeartRate()<Double.parseDouble(scoreList.get("end").toString())){
                        healthy.setHeartRateExpre(scoreList.get("expression").toString());
                        totalScore+=Integer.parseInt(scoreList.get("value").toString());
                    }
                }
            }
            if (healthy.getBloodGlucose() != null){
                //设置血糖表现
                for (Map<String, Object> scoreList : scores.get(SCORES[1])) {
                    if (Double.parseDouble(scoreList.get("start").toString())<=healthy.getBloodGlucose()
                            && healthy.getBloodGlucose()<Double.parseDouble(scoreList.get("end").toString())){
                        healthy.setBloodGlucoseExpre(scoreList.get("expression").toString());
                        totalScore+=Integer.parseInt(scoreList.get("value").toString());
                    }
                }
            }
            if (healthy.getBloodOxygen() != null){
                //设置血氧表现
                for (Map<String, Object> scoreList : scores.get(SCORES[2])) {
                    if (Double.parseDouble(scoreList.get("start").toString())<=healthy.getBloodOxygen()
                            && healthy.getBloodOxygen()<Double.parseDouble(scoreList.get("end").toString())){
                        healthy.setBloodOxygenExpre(scoreList.get("expression").toString());
                        totalScore+=Integer.parseInt(scoreList.get("value").toString());
                    }
                }
            }

            if (healthy.getBloodFat() != null){
                //设置血脂表现
                for (Map<String, Object> scoreList : scores.get(SCORES[3])) {
                    if (Double.parseDouble(scoreList.get("start").toString())<=healthy.getBloodFat()
                            && healthy.getBloodFat()<Double.parseDouble(scoreList.get("end").toString())){
                        healthy.setBloodFatExpre(scoreList.get("expression").toString());
                        totalScore+=Integer.parseInt(scoreList.get("value").toString());
                    }
                }
            }

            if (healthy.getBloodPressure() != null){
                //设置血压表现
                for (Map<String, Object> scoreList : scores.get(SCORES[4])) {
                    if (Double.parseDouble(scoreList.get("start").toString())<=healthy.getBloodPressure()
                            && healthy.getBloodPressure()<Double.parseDouble(scoreList.get("end").toString())){
                        healthy.setBloodPressureExpre(scoreList.get("expression").toString());
                        totalScore+=Integer.parseInt(scoreList.get("value").toString());
                    }
                }
            }
            if(healthy.getBloodFat() != null){
                //设置膳食表现
                for (Map<String, Object> scoreList : scores.get(SCORES[5])) {
                    if (Double.parseDouble(scoreList.get("start").toString())<=healthy.getFood()
                            && healthy.getFood()<Double.parseDouble(scoreList.get("end").toString())){
                        healthy.setFoodExpre(scoreList.get("expression").toString());
                        totalScore+=Integer.parseInt(scoreList.get("value").toString());
                    }
                }
            }

            //设置总表现
            for (Map<String, Object> scoreList : scores.get(SCORES[6])) {
                if (Double.parseDouble(scoreList.get("start").toString())<=totalScore
                        && totalScore<Double.parseDouble(scoreList.get("end").toString())){
                    healthy.setExpression(scoreList.get("expression").toString());
                }
            }

            healthy.setScore(totalScore);
            healthy.setLastUpdate(new Date());

        }
        Example example = new Example(Healthy.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("handicappedId",healthy.getHandicappedId());
        int update = healthyMapper.updateByExampleSelective(healthy, example);

        List<Healthy> healthies = healthyMapper.selectByExample(example);
        redisTemplate.delete("healthy:"+healthy.getHandicappedId());
        redisTemplate.opsForValue().set("healthy:"+healthy.getHandicappedId(),healthy);
        if (update !=1){
            throw new BusinessException(ExceptionCode.UPDATE_FALSE);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("更新成功!");
        return jsonResult.getDataMap();
    }

    @Override
    public Healthy selectById(Long id) throws BusinessException {
        Healthy healthy = mapper.selectByPrimaryKey(id);
        if (healthy == null){
            throw  new BusinessException(ExceptionCode.DELETE_DEFEATED);
        }
        return  healthy;
            }

    @Override
    public List selectHealthy(HealthWhere healthWhere) {
        List<HealthyDetails> healthyDetails = healthyMapper.selectHealthy(healthWhere);
        return healthyDetails;
    }
}
